#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <unistd.h>
#include "comm.hpp"


class Init
{
public:
    Init()
    {
        bool r = MakeFifo();
        if(!r)
        return;
        key_t key = GetKey();
        cout << "key : " << ToHex(key) << endl;
        // sleep(3);
        // shmid: 应用这个共享内存的时候，我们使用shmid来进行操作共享内存， FILE*
        // key: 不要在应用层使用，只用来在内核中标识shm的唯一性！， fd
        int shmid = CreateShm(key);
        cout << "shmid: " << shmid << endl;
        // sleep(10);
    
       cout << "开始将shm映射到进程的地址空间中" << endl;
       s = (char*)shmat(shmid, nullptr, 0);

       fd = open(filename.c_str(), O_RDONLY);

    }

    ~Init()
    {
        shmdt(s);
        cout << "开始将shm从进程的地址空间中移除" << endl;
        shmctl(shmid, IPC_RMID, nullptr);
        cout << "开始将shm从OS中删除" << endl;
        close(fd);
        unlink(filename.c_str());

    }
public:
    int shmid;
    int fd;
    char *s;
};

int main()
{
    Init init;

    //TODO
    while(true)
    {
        //wait
        int code = 0;
        ssize_t n = read(init.fd, &code, sizeof(code));
        if(n > 0)
        {
            //直接读取
            cout << "共享内存的内容: " <<  init.s << endl;
            sleep(1); 
        }
        else if(n == 0)
        {
            break;
        }
    }
    sleep(10);
    
    return 0;
}


